﻿Imports System.Web.UI.WebControls
Imports System.Text
Imports System.Collections.Specialized
Imports System.Web.UI
Imports DotNetNuke.Security.Roles

Namespace DotNetNuke.Modules.ActiveForums.Controls
    Partial Public Class admin_securitygrid
        Inherits ActiveAdminBase
        Public imgOn As String
        Public imgOff As String
        Private _permissionsInfo As PermissionInfo
        Private _permissionsId As Integer = -1
        Private _readOnly As Boolean = False
        Public Property [ReadOnly]() As Boolean
            Get
                Return _readOnly
            End Get
            Set(ByVal value As Boolean)
                _readOnly = value
            End Set
        End Property
        'Public ReadOnly Property IsCallBack() As Boolean
        '    Get
        '        Return cbSecurityToggle.IsCallback
        '    End Get
        'End Property
        Public Property Perms() As PermissionInfo
            Get
                Return _permissionsInfo
            End Get
            Set(ByVal value As PermissionInfo)
                _permissionsInfo = value
            End Set
        End Property
        Public Property PermissionsId() As Integer
            Get
                Return _permissionsId
            End Get
            Set(ByVal value As Integer)
                _permissionsId = value
            End Set
        End Property
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            imgOn = Page.ResolveUrl("~/DesktopModules/ActiveForums/images/admin_check.png")
            imgOff = Page.ResolveUrl("~/DesktopModules/ActiveForums/images/admin_stop.png")
            BindRoles()
            If [ReadOnly] Then
                gridActions.Visible = False
            End If
            BuildNewGrid(Perms, PermissionsId)

        End Sub
        Private Sub BindRoles()
            Dim sb As New StringBuilder
            sb.Append("<select id=""drpSecRoles"" class=""amcptxtbx"" style=""width:150px;"">")
            sb.Append("<option value="""">[RESX:DropDownDefault]</option>")
            sb.Append("<option value=""-1"">All Users</option>")
            sb.Append("<option value=""-3"">Unauthenticated Users</option>")
            Dim rc As New DotNetNuke.Security.Roles.RoleController
            For Each ri As DotNetNuke.Security.Roles.RoleInfo In rc.GetPortalRoles(PortalId)
                sb.Append("<option value=""" & ri.RoleID & """>" & ri.RoleName & "</option>")
            Next
            'drpSecRoles.DataTextField = "RoleName"
            'drpSecRoles.DataValueField = "RoleId"
            'drpSecRoles.DataSource = rc.GetPortalRoles(PortalId)
            'drpSecRoles.DataBind()
            'drpSecRoles.Items.Insert(0, New ListItem("[RESX:DropDownDefault]", ""))
            'drpSecRoles.Items.Insert(1, New ListItem("All Users", "-1"))
            'drpSecRoles.Items.Insert(2, New ListItem("Unauthenticated Users", "-3"))
            'drpSecRoles.Items.Insert(3, New ListItem("Topic Author", "-10"))
            Dim sGroups As String = String.Empty
#If SKU <> "LITE" Then
            If IO.File.Exists(Server.MapPath("~/bin/active.modules.social.dll")) Then
                Dim social As New Social
                Using dr As IDataReader = social.ActiveSocialListGroups(PortalId)
                    While dr.Read()
                        sb.Append("<optgroup label=""" & dr("GroupName").ToString & """>")
                        sb.Append("<option value=""" & dr("GroupId").ToString & ":0"">Group Admin</option>")
                        sb.Append("<option value=""" & dr("GroupId").ToString & ":1"">Group Member</option>")
                        sb.Append("</optgroup>")

                    End While
                    dr.Close()
                End Using
            End If
#End If
            sb.Append("</select>")
            litRoles.Text = sb.ToString
        End Sub
        Private Sub BuildNewGrid(ByVal security As PermissionInfo, ByVal permissionsId As Integer)
            'Roles
            Dim roles() As String = GetSecureObjectList(security, 0).Split(CChar(";"))
            Dim roleIds(roles.Length - 2) As Integer
            Dim i As Integer = 0
            For i = 0 To roles.Length - 2
                If Not String.IsNullOrEmpty(roles(i)) Then
                    roleIds(i) = CInt(roles(i))
                End If
            Next
            Array.Sort(roleIds)
            Dim tmp As String = String.Empty
            For Each n As Integer In roleIds
                tmp &= n.ToString & ";"
            Next
            Dim pl As New List(Of PermissionInfo)

            'litNewGrid.Text = "Roles:" & tmp

            'litNewGrid.Text &= "<br />RolesNames:" & Permissions.GetRolesNVC(tmp)
            Dim nvc As NameValueCollection = Permissions.GetRolesNVC(tmp, PortalId)
            Dim rc As New RoleController
            For Each key As String In nvc.AllKeys
                Dim pi As New PermissionInfo
                With pi
                    .ObjectId = key
                    .ObjectName = nvc.Item(key)
                    If String.IsNullOrEmpty(.ObjectName) Then
                        .ObjectName = rc.GetRole(CInt(key), PortalId).RoleName
                    End If
                    .Type = ObjectType.RoleId
                End With
                pl.Add(pi)
            Next

            'Users
            Dim users As String = GetSecureObjectList(security, 1)
            Dim userNames As String = String.Empty
            If Not String.IsNullOrEmpty(users) Then
                Dim uc As New DotNetNuke.Entities.Users.UserController
                For Each uid As String In users.Split(CChar(";"))
                    If Not String.IsNullOrEmpty(uid) Then
                        Dim u As DotNetNuke.Entities.Users.UserInfo = uc.GetUser(PortalId, CInt(uid))
                        If Not u Is Nothing Then
                            Dim pi As New PermissionInfo
                            With pi
                                .ObjectId = u.UserID.ToString
                                .ObjectName = u.DisplayName
                                .Type = ObjectType.UserId
                            End With
                            pl.Add(pi)
                        End If

                    End If
                Next
            End If
            'Groups
            Dim groups As String = GetSecureObjectList(security, 2)
            If Not String.IsNullOrEmpty(groups) Then
                For Each g As String In groups.Split(CChar(";"))
                    If Not String.IsNullOrEmpty(g) Then

                        Dim gType As String = g.Split(CChar(":"))(1)
                        Dim groupId As Integer = CInt(g.Split(CChar(":"))(0))
                        Dim role As RoleInfo = rc.GetRole(groupId, PortalId)
                        Dim groupName As String = role.RoleName
                        If Not String.IsNullOrEmpty(groupName) Then
                            Dim pi As New PermissionInfo
                            With pi
                                .ObjectId = g
                                .ObjectName = groupName
                                .Type = ObjectType.GroupId
                            End With
                            If CInt(gType) = 0 Then
                                pi.ObjectName &= " - Owner"
                            Else
                                pi.ObjectName &= " - Member"
                            End If
                            pl.Add(pi)
                        End If
                    End If
                Next
            End If

            Dim grid(pl.Count, 27) As String
            i = 0
            For Each pi As PermissionInfo In pl
                grid(i, 0) = pi.ObjectId
                grid(i, 1) = pi.ObjectName
                grid(i, 2) = CStr(pi.Type)
                grid(i, 3) = CStr(PermValue(pi.Type, pi.ObjectId, security.View))
                grid(i, 4) = CStr(PermValue(pi.Type, pi.ObjectId, security.Read))
                grid(i, 5) = CStr(PermValue(pi.Type, pi.ObjectId, security.Create))
                grid(i, 6) = CStr(PermValue(pi.Type, pi.ObjectId, security.Reply))
                grid(i, 7) = CStr(PermValue(pi.Type, pi.ObjectId, security.Edit))
                grid(i, 8) = CStr(PermValue(pi.Type, pi.ObjectId, security.Delete))
                grid(i, 9) = CStr(PermValue(pi.Type, pi.ObjectId, security.Lock))
                grid(i, 10) = CStr(PermValue(pi.Type, pi.ObjectId, security.Pin))
                grid(i, 11) = CStr(PermValue(pi.Type, pi.ObjectId, security.Attach))
                grid(i, 12) = CStr(PermValue(pi.Type, pi.ObjectId, security.Poll))
                grid(i, 13) = CStr(PermValue(pi.Type, pi.ObjectId, security.Block))
                grid(i, 14) = CStr(PermValue(pi.Type, pi.ObjectId, security.Trust))
                grid(i, 15) = CStr(PermValue(pi.Type, pi.ObjectId, security.Subscribe))
                grid(i, 16) = CStr(PermValue(pi.Type, pi.ObjectId, security.Announce))
                grid(i, 17) = CStr(PermValue(pi.Type, pi.ObjectId, security.Tag))
                grid(i, 18) = CStr(PermValue(pi.Type, pi.ObjectId, security.Categorize))
                grid(i, 19) = CStr(PermValue(pi.Type, pi.ObjectId, security.Prioritize))

                grid(i, 20) = CStr(PermValue(pi.Type, pi.ObjectId, security.ModApprove))
                grid(i, 21) = CStr(PermValue(pi.Type, pi.ObjectId, security.ModMove))
                grid(i, 22) = CStr(PermValue(pi.Type, pi.ObjectId, security.ModSplit))
                grid(i, 23) = CStr(PermValue(pi.Type, pi.ObjectId, security.ModDelete))
                grid(i, 24) = CStr(PermValue(pi.Type, pi.ObjectId, security.ModUser))
                grid(i, 25) = CStr(PermValue(pi.Type, pi.ObjectId, security.ModEdit))
                grid(i, 26) = CStr(PermValue(pi.Type, pi.ObjectId, security.ModLock))
                grid(i, 27) = CStr(PermValue(pi.Type, pi.ObjectId, security.ModPin))


                i += 1
            Next
            Dim enumType As System.Type = GetType(SecureActions)
            Dim values As Array = [Enum].GetValues(enumType)
            Dim sb As New StringBuilder
            sb.Append("<table cellpadding=""0"" cellspacing=""0""><tr><td valign=""top""><div class=""afsecobjects""><table cellpadding=""0"" cellspacing=""0"" border=""0"">")
            sb.Append("<tr><td class=""afsecobjecthd"" colspan=""2"">" & Utilities.GetSharedResource("[RESX:SecureObjects]", True) & "</td></tr>")
            Dim tmpObjectName As String = String.Empty
            Dim secRows As Integer = 0
            For x As Integer = 0 To pl.Count - 1
                sb.Append("<tr><td style=""width:16px;""></td><td class=""afsecobject"" style=""white-space:nowrap;""><div class=""afsecobjecttxt"" title=""" & grid(x, 1) & """ onmouseover=""this.firstChild.style.display='';"" onmouseout=""this.firstChild.style.display='none';""><span style=""width:16px;height:16px;float:right;display:none;"">")
                If (CInt(grid(x, 2)) = 0 AndAlso CInt(grid(x, 0)) > 0) Or CInt(grid(x, 2)) > 0 Then
                    If Not [ReadOnly] Then
                        sb.Append("<img src=""" & Page.ResolveUrl("~/DesktopModules/ActiveForums/images/mini_del.gif") & """ alt=""Remove Object"" style=""cursor:pointer;z-index:10;"" class=""afminidel"" onclick=""securityDelObject(this,'" & grid(x, 0) & "'," & grid(x, 2) & "," & permissionsId & ");"" />")
                    End If
                End If
                sb.Append("</span>" & grid(x, 1))
                sb.Append("</div></td></tr>")
            Next
            sb.Append("</table></div></td><td valign=""top"" width=""94%""><div class=""afsecactions"" style=""overflow-x:auto;overflow-y:hidden;"">")
            'litNewObjects.Text = sb.ToString
            'sb = New StringBuilder

            sb.Append("<table cellpadding=0 cellspacing=0 border=0 width=""100%"" id=""tblSecGrid"">")
            sb.Append("<tr>")
            Dim keyText As String = String.Empty
            For td As Integer = 3 To 27
                keyText = Convert.ToString([Enum].Parse(enumType, values.GetValue(td - 3).ToString()))
                If keyText.ToLowerInvariant = "block" Then
                    sb.Append("<td class=""afsecactionhd"" style=""display:none;"">")
                Else
                    sb.Append("<td class=""afsecactionhd"">")
                End If


                sb.Append(keyText)
                sb.Append("</td>")
            Next
            sb.Append("</tr>")
            For x As Integer = 0 To pl.Count - 1
                sb.Append("<tr onmouseover=""this.className='afgridrowover'"" onmouseout=""this.className='afgridrow'"">")
                For r As Integer = 3 To 27
                    keyText = Convert.ToString([Enum].Parse(enumType, values.GetValue(r - 3).ToString()))
                    Dim bState As Boolean = CBool(grid(x, r)) 'Permissions.HasPermission(ForumID, Integer.Parse(dr("ObjectId").ToString), key, Integer.Parse(dr("SecureType").ToString), dt)
                    Dim sState As String = "<img src=""" & imgOff & """ alt=""Disabled"" />"
                    If bState Then
                        sState = "<img src=""" & imgOn & """ alt=""Enabled"" />"
                    End If
                    If keyText.ToLowerInvariant = "block" Then
                        sb.Append("<td class=""afsecactionelem"" style=""text-align:center;display:none;"">")
                    Else
                        sb.Append("<td class=""afsecactionelem"" style=""text-align:center;"">")
                    End If

                    sb.Append("<div class=""afsectoggle"" id=""" & grid(x, 0) & grid(x, 2) & keyText & """ ")
                    If Not [ReadOnly] Then
                        sb.Append("onclick=""securityToggle(this," & permissionsId & ",'" & grid(x, 0) & "','" & grid(x, 1) & "'," & grid(x, 2) & ",'" & keyText & "');""")
                    End If
                    sb.Append(">" & sState & "</div></td>")


                Next
                sb.Append("</tr>")
            Next
            sb.Append("</table></div></td></tr></table>")
            litSecGrid.Text = sb.ToString
            'litNewSecurity.Text = sb.ToString
            'litNewGrid.Text = sb.ToString

        End Sub
        Private Function PermValue(ByVal objectType As Integer, ByVal objectId As String, ByVal permSet As String) As Boolean
            If String.IsNullOrEmpty(permSet) Then
                Return False
            Else
                Return Permissions.HasAccess(permSet.Split(CChar("|"))(objectType), objectId & ";")
            End If

        End Function

        Private Function GetSecureObjectList(ByVal s As PermissionInfo, ByVal objectType As Integer) As String
            Dim roleObjects As String = String.Empty

            roleObjects = GetObjFromSecObj(s.Announce, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.Attach, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.Categorize, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.Create, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.Delete, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.Edit, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.Lock, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.ModApprove, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.ModDelete, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.ModEdit, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.ModLock, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.ModMove, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.ModPin, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.ModSplit, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.ModUser, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.Pin, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.Poll, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.Prioritize, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.Read, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.Reply, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.Subscribe, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.Tag, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.Trust, objectType, roleObjects)
            roleObjects = GetObjFromSecObj(s.View, objectType, roleObjects)





            Return roleObjects
        End Function
        Private Function GetObjFromSecObj(ByVal permSet As String, ByVal index As Integer, ByVal objects As String) As String
            If String.IsNullOrEmpty(permSet) Then
                permSet = PortalSettings.AdministratorRoleId & ";||||"
            End If
            Dim perms() As String = permSet.Split(CChar("|"))
            If Not perms(index) Is Nothing Then
                If Not String.IsNullOrEmpty(perms(index)) Then
                    For Each s As String In perms(index).Split(CChar(";"))
                        If Not String.IsNullOrEmpty(s) Then
                            If Array.IndexOf(objects.Split(CChar(";")), s) = -1 Then
                                objects &= s & ";"
                            End If
                        End If
                    Next
                End If
            End If

            Return objects
        End Function
        Private Sub cbSecurityToggle_Callback(ByVal sender As Object, ByVal e As CallBackEventArgs) Handles cbSecurityToggle.Callback
            Dim action As String = e.Parameters(0).ToString
            Dim pId As Integer = PermissionsId
            Dim secId As String = e.Parameters(2).ToString
            Dim secType As Integer = CInt(e.Parameters(3).ToString)
            Dim key As String = e.Parameters(4).ToString
            Dim returnId As String = e.Parameters(5).ToString
            Dim db As New Data.Common
            Dim sOut As String = String.Empty
            If action = "delete" Then
                Permissions.RemoveObjectFromAll(secId, secType, pId)

            ElseIf action = "addobject" Then
                If secType = 1 Then
                    Dim uc As New UserController
                    Dim ui As User = uc.GetUser(PortalId, ModuleId, secId)
                    If Not ui Is Nothing Then
                        secId = ui.UserId.ToString
                    Else
                        secId = String.Empty
                    End If
                Else
                    If secId.Contains(":") Then
                        secType = 2
                    End If
                End If
                If Not String.IsNullOrEmpty(secId) Then
                    Dim permSet As String = db.GetPermSet(pId, "View")
                    permSet = Permissions.AddPermToSet(secId, secType, permSet)
                    db.SavePermSet(pId, "View", permSet)
                End If


            Else
                Dim permSet As String = db.GetPermSet(pId, key)
                If action = "remove" Then
                    permSet = Permissions.RemovePermFromSet(secId, secType, permSet)
                Else
                    permSet = Permissions.AddPermToSet(secId, secType, permSet)
                End If
                db.SavePermSet(pId, key, permSet)
                sOut = action & "|" & returnId
            End If
            Dim lit As New LiteralControl(sOut)
            lit.RenderControl(e.Output)
        End Sub

        Private Sub cbSecGrid_Callback(ByVal sender As Object, ByVal e As CallBackEventArgs) Handles cbSecGrid.Callback
            BuildNewGrid(Perms, PermissionsId)
            litSecGrid.RenderControl(e.Output)
        End Sub
    End Class
End Namespace
